package com.liuxu.supernews;

import android.graphics.Rect;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.view.accessibility.AccessibilityNodeInfo;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class utils {
    private boolean run=true;
    private int screenWidth;
    private int screenHeight;
    private Process p;
    private DataOutputStream os;
    private DataInputStream is;
    public utils(){
        try {
            p = Runtime.getRuntime().exec("su");
            os=new DataOutputStream(p.getOutputStream());
            is=new DataInputStream(p.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public final void execShellCmd(String cmd) {
        try {
            if (os==null&&run){
                os=new DataOutputStream(Runtime.getRuntime().exec("su").getOutputStream());
            }
            if (run) {
                os.writeBytes(cmd + "\n");
                os.flush();
                Log.v("命令",cmd);
            }else {
                Log.v("不执行",cmd);
                p.destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public final void Open(String activity) throws IOException, InterruptedException {
            if (os==null){
                os=new DataOutputStream(Runtime.getRuntime().exec("su").getOutputStream());
            }
            if (run) {
                os.writeBytes("am start -n "+activity+ "\n");
            }
        Thread.sleep(4000);
    }
    public String execShellCmdget(String cmd) throws IOException {
        try {
                Process p = Runtime.getRuntime().exec("su");
                os = new DataOutputStream(p.getOutputStream());
                is = new DataInputStream(p.getInputStream());
                os.writeBytes(cmd + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer result = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            result.append(new String(b, 0, n));
        }
        return result.toString();
    }
//    public void eexecShellCmd(String cmd) {
//        try {
//            // 申请获取root权限
//            Process process = Runtime.getRuntime().exec("su");
//            // 获取输出流
//            OutputStream outputStream = process.getOutputStream();
//            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
//            dataOutputStream.writeBytes(cmd);
//            dataOutputStream.flush();
//            dataOutputStream.close();
//            outputStream.close();
//        } catch (Throwable t) {
//            t.printStackTrace();
//        }
//    }
    public void Click(int a,int b) throws InterruptedException {
            String x = String.valueOf((int)((a*screenWidth)/720));
            String y = String.valueOf((int)((b*screenHeight) /1280));
            execShellCmd("input tap " + x + " " + y+"\n");
            Thread.sleep(2000);
    }
    public void Back() throws InterruptedException {
        Thread.sleep(4000);
            execShellCmd("input keyevent 4");
    }
    public void Home(){
        execShellCmd("input keyevent 3");
    }
    public void Key_up(int time) throws InterruptedException {
        while (time>0){
            Thread.sleep(1100);
            execShellCmd("input keyevent 20");
            time-=1;
        }
    }
    public void Key_down(int time) throws InterruptedException {
        while (time>0){
            Thread.sleep(1100);
            execShellCmd("input keyevent 19");
            time-=1;
        }
    }
    public void Close(String packagename){
        execShellCmd("input keyevent 3");
        execShellCmd("am force-stop "+packagename);
    }

    public void swipe(int x1,int y1,int x2,int y2,int time){
        String a = String.valueOf((int)((x1*screenWidth)/720));
        String b= String.valueOf((int)((y1*screenHeight) /1280));
        String c = String.valueOf((int)((x2*screenWidth)/720));
        String d = String.valueOf((int)((y2*screenHeight) /1280));
        execShellCmd("input swipe "+a+" "+b+" "+c+" "+d+" "+time);
    }

    public void swipe_up(int time,int speed) throws InterruptedException {
        String x1 = String.valueOf((int)((300*screenWidth)/720));
        String y1= String.valueOf((int)((800*screenHeight) /1280));
        String x2 = String.valueOf((int)((500*screenWidth)/720));
        String y2 = String.valueOf((int)((500*screenHeight) /1280));
        while (time>0){
            execShellCmd("input swipe "+x1+" "+y1+" "+x2+" "+y2+" "+speed);
            time-=1;
            Thread.sleep(1100);
        }
    }

    public void swipe_down(int time,int speed) throws InterruptedException {
        String x1 = String.valueOf((int)((500*screenWidth)/720));
        String y1= String.valueOf((int)((500*screenHeight) /1280));
        String x2 = String.valueOf((int)((300*screenWidth)/720));
        String y2 = String.valueOf((int)((800*screenHeight) /1280));
        while (time>0){
            execShellCmd("input swipe "+x1+" "+y1+" "+x2+" "+y2+" "+speed);
            time-=1;
            Thread.sleep(1100);

        }
    }
    public void quick_up(int time) throws InterruptedException {
        String x1 = String.valueOf((int)((300*screenWidth)/720));
        String y1= String.valueOf((int)((1000*screenHeight) /1280));
        String x2 = String.valueOf((int)((400*screenWidth)/720));
        String y2 = String.valueOf((int)((300*screenHeight) /1280));
        while (time>0){
            execShellCmd("input swipe "+x1+" "+y1+" "+x2+" "+y2+" "+"100");
            time-=1;
            Thread.sleep(1100);
        }
    }

    public void quick_down(int time) throws InterruptedException {
        String x1 = String.valueOf((int)((400*screenWidth)/720));
        String y1= String.valueOf((int)((300*screenHeight) /1280));
        String x2 = String.valueOf((int)((300*screenWidth)/720));
        String y2 = String.valueOf((int)((1000*screenHeight) /1280));
        while (time>0){
            execShellCmd("input swipe "+x1+" "+y1+" "+x2+" "+y2+" "+"100");
            time-=1;
            Thread.sleep(1100);

        }
    }
    public void readsometimebykey(String activity, int time, int uptime, int downtime, int a, int b, boolean click) throws InterruptedException, IOException {
        while (time>0){
            readonebykey(uptime,downtime,a,b,click);
            swipe_up(2,300);
            Back();
            swipe_up(4,300);
            Back();
            Open(activity);
            readtwobykey(uptime,downtime,a,b,click);
            swipe_up(2,300);
            Back();
            swipe_up(4,300);
            Back();
            Open(activity);
            time-=1;
        }
    }
    public void readsometimebytp(String activity, int time, int uptime, int quickuptime, int quickdowntime, int downtime, int speed, int a, int b, boolean click) throws InterruptedException, IOException {
        while (time>0){
            readonebytp(uptime,quickuptime,quickdowntime,downtime,a,b,click);
            swipe_up(2,speed);
            Back();
            swipe_up(2,speed);
            Back();
            swipe_up(2,speed);
            Open(activity);
            readtwobytp(uptime,quickuptime,quickdowntime,downtime,a,b,click);
            swipe_up(2,speed);
            Back();
            swipe_up(2,speed);
            Back();
            swipe_up(2,speed);
            Open(activity);
            time-=1;
        }
    }
    public void readonebykey(int uptime,int downtime,int a,int b,boolean click) throws InterruptedException {
        Click(350,400);
        Thread.sleep(2000);
        readslowbykey(uptime,downtime,a,b,click);
    }
    public void readtwobykey(int uptime,int downtime,int a,int b,boolean click) throws InterruptedException {
        Click(400,950);
        Thread.sleep(2000);
        readslowbykey(uptime,downtime,a,b,click);
    }
    public void readonebytp(int uptime,int quickuptime,int quickdowntime,int downtime,int a,int b,boolean click) throws InterruptedException {
        Click(350,400);
        Thread.sleep(2000);
        readslowbytp(uptime,quickuptime,quickdowntime,downtime,a,b,click);
    }
    public void readtwobytp(int uptime,int quickuptime,int quickdowntime,int downtime,int a,int b,boolean click) throws InterruptedException {
        Click(400,950);
        Thread.sleep(2000);
        readslowbytp(uptime,quickuptime,quickdowntime,downtime,a,b,click);
    }
    public void readslowbykey(int uptime,int downtime,int a,int b,boolean click) throws InterruptedException {
        Key_up(uptime);
        Key_down(downtime);
        if (click){
            Click(a,b);
        }
        Back();
    }
    public void readslowbytp(int uptime,int quickuptime,int quickdowntime,int downtime,int a,int b,boolean click) throws InterruptedException {
        swipe_up(uptime,200);
        quick_up(quickuptime);
        quick_down(quickdowntime);
        swipe_down(downtime,200);
        if (click){
            Click(a,b);
        }
        Back();
    }
    public void updownbykey(int uptime,int downtime) throws InterruptedException {
        Key_up(uptime);
        Key_down(downtime);
    }
    public int getScreenWidth() {
        return screenWidth;
    }

    public void setScreenWidth(int screenWidth) {
        this.screenWidth = screenWidth;
    }

    public int getScreenHeight() {
        return screenHeight;
    }

    public void setScreenHeight(int screenHeight) {
        this.screenHeight = screenHeight;
    }

    public void setRun(boolean run) {
        this.run = run;
    }
    public String GetBondsByText(String text) throws XmlPullParserException, IOException {
        XmlPullParser xpp = Xml.newPullParser();
        File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/window_dump.xml");
        InputStream inputStream =new FileInputStream(file);
        xpp.setInput(inputStream, "utf-8");
        int type = xpp.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if (xpp.getAttributeName(0).equals("index")) {
                        if (xpp.getAttributeValue(1).equals(text)) {
                            String bonds=xpp.getAttributeValue(16);
                            Log.v("通过文字找到坐标",bonds);
                            return bonds;
                        }else {
                            Log.v("通过文字找到坐标",xpp.getAttributeValue(1));
                        }
                    }
                case XmlPullParser.END_TAG:
                    if (xpp.getName().equals("hierarchy")){
                        break;
                    }
            }
            type=xpp.next();
        }
        return "";
    }
    public String GetBondsById(String text) throws XmlPullParserException, IOException {
        XmlPullParser xpp = Xml.newPullParser();
        File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/window_dump.xml");
        InputStream inputStream =new FileInputStream(file);
        xpp.setInput(inputStream, "utf-8");
        int type = xpp.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if (xpp.getAttributeName(0).equals("index")) {
                        if (xpp.getAttributeValue(2).equals(text)) {
                            String bonds=xpp.getAttributeValue(16);
                            Log.v("通过类名找到坐标",bonds);
                            return bonds;
                        }
                    }
            }
            type=xpp.next();
        }
        return "";
    }
    public List GetRect(String bonds) {
        List<String> rect = new ArrayList<>();
        String pattern = "\\d+";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(bonds);
        int i=0;
        while (m.find( )) {
            rect.add(m.group());
        }
        return rect;
    }
    public Rect FindRectByText(String text) throws InterruptedException, IOException, XmlPullParserException {
        execShellCmd("uiautomator dump");
        Thread.sleep(2000);
        int time=5;
        String bonds="";
        while (time>1&bonds.equals("")){
            bonds=GetBondsByText(text);
            Thread.sleep(2000);
        }
        Rect rect = new Rect();
        if (bonds.equals("")){
            return null;
        }else {
            List<String> rectlist=GetRect(bonds);
            rect.left= Integer.parseInt(rectlist.get(0));
            rect.left= Integer.parseInt(rectlist.get(1));
            rect.left= Integer.parseInt(rectlist.get(2));
            rect.left= Integer.parseInt(rectlist.get(3));
        }
        return rect ;
    }
    public Rect FindRectById(String text) throws InterruptedException, IOException, XmlPullParserException {
        execShellCmd("uiautomator dump");
        Thread.sleep(3000);
        int time=5;
        String bonds=null;
        while (time>1&bonds.equals("")){
            bonds=GetBondsById(text);
            Thread.sleep(2000);
        }
        Rect rect = new Rect();
        if (bonds.equals("")){
            return null;
        }else {
            List<String> rectlist=GetRect(bonds);
            rect.left= Integer.parseInt(rectlist.get(0));
            rect.left= Integer.parseInt(rectlist.get(1));
            rect.left= Integer.parseInt(rectlist.get(2));
            rect.left= Integer.parseInt(rectlist.get(3));
        }
        return rect ;
    }
    public void ClickRect(Rect rect){
        String x = String.valueOf((rect.left + rect.right) / 2);
        String y = String.valueOf((rect.top + rect.bottom) / 2);
        execShellCmd("input tap " + x + " " + y);
    }
    public void ClickNode(List<AccessibilityNodeInfo> Node) throws InterruptedException {
        if(Node.size()!=0) {
            Rect rect = new Rect();
            Node.get(0).getBoundsInScreen(rect);
            String x = String.valueOf((rect.left + rect.right) / 2);
            String y = String.valueOf((rect.top + rect.bottom) / 2);
            Thread.sleep(1000);
            Log.v("找到控件","进行点击");
            execShellCmd("input tap " + x + " " + y);
        }
        else {
            Log.v("未发现控件","尴尬");
        }
    }
    public void NodeClick(List<AccessibilityNodeInfo> Node) throws InterruptedException {
        if(Node.size()!=0) {
            Log.v("找到控件","进行点击");
            Node.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
        else {
            Log.v("未发现控件","尴尬");
        }
    }

}
